package com.rover.system.service;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.grid.DataGrid;
import com.rover.system.entity.SysParam;
import org.apache.commons.lang.StringUtils;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.grid.Page;
import com.rover.system.dao.BaseDao;


@Service("sysParamService")
@Transactional
public class SysParamService{
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private BaseDao dao;
	
	@Transactional
    public DataGrid query(Page page,Map<String, Object> params,String hql){
        DataGrid dataGrid=new DataGrid();
		hql = "from SysParam" + hql;
        dataGrid.setResult(dao.<SysParam>findPageHql(hql, params, page.getPageNo(),
				page.getPageSize()));
		String totalHql = "select count(*) " + hql;
        dataGrid.setTotalCount(dao.countHql(totalHql, params));
	    return dataGrid;
	}
	
	@Transactional
    public void save(SysParam param){
        dao.saveOrUpdate(param);
	}
	
	@Transactional
    public void delete(Long id){
        dao.delete(SysParam.class, id);
	}
	

	
	/*
	 * 获取参数对应的值
	 * @Code  参数名称
	 * */
	@Transactional
    public String getCodeValue(String paramCode){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("paramCode", paramCode);
		List<SysParam>  li=dao.findHql("from SysParam where paramCode=:paramCode", params);
		if(li.size()>0)
		return li.get(0).getParamVal();
		else{
			return "";
		}
	}
	
	 //初始
	@Transactional
    public void initData() throws ServiceException{
		
        logger.debug("开始装载系统参数初始数据");
        File resourcetxt = new File(this.getClass().getResource("/data/appsetup.txt").getFile());
        String star[] = {};
        try {
            List<String> lines = Files.readLines(resourcetxt, Charsets.UTF_8);
            SysParam sysParam;
            int line = 1;
            for (String thisLine : lines) {
                //第一行是标题
                if (line == 1) {
                    line++;
                    continue;
                }
                Iterable<String> s = Splitter.on(",").split(thisLine);
                star = Iterables.toArray(s, String.class);

                if (star[0].trim().equals(""))
                    continue;
                Map<String, Object> params = new HashMap<String, Object>();
        		params.put("paramCode", star[0].trim());
                List<SysParam> liSysParam = dao.findHql("from SysParam where paramCode=:paramCode", params);
                if (liSysParam != null && liSysParam.size() != 0) {
                    continue;
                }
                sysParam = new SysParam();
                sysParam.setParamCode(star[0].trim());
                sysParam.setParamVal(star[1].trim());
                sysParam.setDescription(star[2].trim());

                this.dao.save(sysParam);
            }
        } catch (Exception e) {
            logger.error("str[]:" + StringUtils.join(star, ","));
            logger.error("装载系统参数数据出错:" + e);
            throw new ServiceException("导入系统参数时，服务器发生异常");
        } finally {
           
        }
    }
}
